package test21.upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPFileUploadServer {
    public static void main(String[] args) throws IOException {
        //服务端在本机监听8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();

        //读取客户端发送的数据
        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        byte[] array = StreamUtils.streamToByteArray(bufferedInputStream);
        //将得到 bytes 数组，写入到指定的路径，就得到一个文件了
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("src\\test2.png"));
        bufferedOutputStream.write(array);
        bufferedOutputStream.flush();
        bufferedOutputStream.close();

        // 向客户端回复 "收到图片"
        // 通过socket 获取到输出流(字符)
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bufferedWriter.write("收到图片");
        bufferedWriter.flush();
        socket.shutdownOutput();

        //关闭其他资源
        bufferedWriter.close();
        bufferedInputStream.close();
        socket.close();
        serverSocket.close();
    }
}
